class PayCustAssignModule extends React.Component {
    constructor(props) {
        super(props);

        this.payAuthority = {
            CAR : 'car:pay',
            CAR_DESC : '车辆进出扫码支付、预出场支付、停车月卡付费等',

            PROPERTY_FEE : 'property:pay',
            PROPERTY_FEE_DESC : '业主居生活APP内支付物业费，账单接收与查询等',
        }

        this.state = {
            wxSecrets: [],
            aliSecrets: [],
            customs: [],
            payModuleInfos:[]
        }

        this.modules = ['CAR', 'PROPERTY_FEE'];
    }


    componentDidMount(){
        this.updateCustomers();
    }

    updateCustomers(){
        postJson("/customer/pay/querySecretByUser.x",null,(data)=>{
            let wxSecrets = data.data.wx;
            let aliSecrets = data.data.ali;
            postJson("/customer/pay/queryCustByUser.x",null,(customs)=>{
                for(let i=0;i<customs.data.length;i++){
                    for(let j=0;j<wxSecrets.length;j++){
                        if(!wxSecrets[j])
                            continue;
                        if(customs.data[i].id === wxSecrets[j].customId) {
                            customs.data[i].mchId = wxSecrets[j].mchId;
                            wxSecrets[j] = null;
                        }
                    }

                    for(let j=0;j<aliSecrets.length;j++){
                        if(!aliSecrets[j])
                            continue;
                        if(customs.data[i].id === aliSecrets[j].customId) {
                            customs.data[i].aliAccount = aliSecrets[j].mchId;
                            aliSecrets[j] = null;
                        }
                    }
                }

                this.setState({
                    customs:customs.data,
                    wxSecrets:wxSecrets,
                    aliSecrets:aliSecrets
                });
            })
        })
    }

    addNewGroup(){
        this.refs.customName.value = "";
        this.refs.modal.show();
    }

    saveGroup(){
        if(this.refs.tableWx.checkboxValue.length == 0 && this.refs.tableAli.checkboxValue.length == 0){
            layui.layer.msg("请选择至少一条数据");
            return;
        }

        let list = [];
        list.push(... this.refs.tableWx.checkboxValue);
        list.push(... this.refs.tableAli.checkboxValue);

        postJson("/customer/pay/saveNewCustomerWithSecrets.x",{customName:this.refs.customName.value,secretsJson : JSON.stringify(list)},()=>{
            layui.layer.msg("保存成功");
            this.refs.modal.close();
            this.updateCustomers();
        })

    }

    wxCheck(checked,data){
        if(checked){
            this.refs.tableWx.checkboxValue = [data];
            this.setState({});
        }
    }

    aliCheck(checked,data){
        if(checked){
            this.refs.tableAli.checkboxValue = [data];
            this.setState({});
        }
    }

    deleteCustomer(id){
        layui.layer.confirm("确定要删除此组么(不会删除微信与支付宝参数)",()=>{
            postJson("/customer/pay/deleteCustomerForUser.x",{id:id},()=>{
                layui.layer.msg("删除成功!");
                this.updateCustomers();
            })
        });

    }

    assignModule(customId){
        let checkValues = [];
        for(let i=0; i<this.state.payModuleInfos.length;i++){
            if(customId === this.state.payModuleInfos[i].customId)
                checkValues.push(this.state.payModuleInfos[i]);
        }

        this.refs.tablePayModule.checkboxValue = checkValues;
        this.setState({});
        this.refs.modalAssign.show({value:customId});
    }

    saveAssign(){
        let customId = this.refs.modalAssign.value;
        let values = this.refs.tablePayModule.checkboxValue;
        if(values.length === 0){
            layui.layer.msg("请至少选择一条数据");
            return;
        }

        let check = [];

        for(let i=0; i<values.length; i++){
            if(customId !== values[i].customId){
                check.push(values[i]);
            }
        }

        if(check.length > 0){
            let checkStr = "";
            for(let i=0; i < check.length; i++)
                checkStr += "【"+check[i].orderDesc+"】已经绑定其他组ID【"+check[i].customId+"】<br/>";

            layui.layer.confirm("发现以下问题:<br>"+checkStr+"确定要覆盖么?",()=>{
                postJson("/pay/assignPayModules.x",{customId : customId,payModuleInfosJson:JSON.stringify(this.refs.tablePayModule.checkboxValue)},()=>{
                    layui.layer.msg("保存成功");
                    this.refs.modalAssign.close();
                })
            })
        }else{
            postJson("/pay/assignPayModules.x",{customId : customId,payModuleInfosJson:JSON.stringify(this.refs.tablePayModule.checkboxValue)},()=>{
                layui.layer.msg("保存成功");
                this.refs.modalAssign.close();
            })
        }

    }

    commChange(comm){
        postAJson("/pay/getPayModulesInfo.x",{commCode:comm,modules:this.modules},(data)=>{
           this.setState({payModuleInfos:data.data});
        });
    }

    goHelp(){
        window.location.href="/api/v3/cms/anon/getContent?ueditorId=help_pay_assign_module&template=UecontentWebWithFrame";
    }

    render(){
        let found = 0;
        if(hasPerms("car:pay | property:pay"))
            found = 1;

        return (
            <Frame header="关联支付账号与消费模块" tips="添加好的微信公众号和支付宝账号必须要捆绑成分组才能分配使用"
                   headerBtns={
                       [
                           <HeaderBtn onClick={()=>this.addNewGroup()}><i className="fa fa-plus"/>&nbsp;新增分组</HeaderBtn>,
                           <HeaderBtn onClick={()=>this.goHelp()}><i className="fa fa-question-circle-o" style={{fontSize:16}}/>&nbsp;帮助文档</HeaderBtn>
                       ]}>

                <Table refs="table">
                    <thead>
                        <tr>
                            <th>系统组ID</th>
                            <th>名称</th>
                            <th>微信商户号</th>
                            <th>支付宝账号</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                    {
                        this.state.customs.length > 0?this.state.customs.map((custom)=>{
                            if(custom) {
                                return (
                                    <tr>
                                        <td>{custom.id}</td>
                                        <td>{custom.customDetail}</td>
                                        <td>{custom.mchId}</td>
                                        <td>{custom.aliAccount}</td>
                                        <td>
                                            <Button btnType="normal" size="xs" onClick={()=>this.assignModule(custom.id)}>绑定支付功能</Button>
                                            <Button btnType="danger" size="xs" onClick={()=>this.deleteCustomer(custom.id)}>删除分组</Button>
                                        </td>
                                    </tr>
                                )
                            }

                        }):''
                    }
                    </tbody>

                </Table>
                <Modal title="选择一个微信和一个支付宝(已绑定分组的参数不可见)" ref="modal" area={['800px']}>
                    <Form type="pane">
                        <Item>
                            <Label>请输入组名</Label>
                            <Input lay-verify="required" ref="customName"/>
                        </Item>
                        <Row>
                            <Col md="6" sm="6" style={{padding : 10}}>
                                <Table ref="tableWx" checkboxKeyname="id">
                                    <thead>
                                        <tr>
                                            <th width={30}>选择</th>
                                            <th>微信商户号</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    {
                                        this.state.wxSecrets.length > 0?this.state.wxSecrets.map((data)=>{
                                            if(data) {
                                                return (
                                                    <tr>
                                                        <td><TCheckbox lay-skin="primary" data={data}
                                                                       tableRef={this.refs.tableWx}
                                                                       onClick={(checked) => this.wxCheck(checked, data)}/>
                                                        </td>
                                                        <td>{data.mchId}</td>
                                                    </tr>
                                                )
                                            }
                                        }):''
                                    }
                                    </tbody>
                                </Table>
                            </Col>
                            <Col md="6" sm="6" style={{padding : 10}}>
                                <Table ref="tableAli" checkboxKeyname="id" >
                                    <thead>
                                    <tr>
                                        <th width={30}>选择</th>
                                        <th>支付宝账号</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {
                                        this.state.aliSecrets.length > 0?this.state.aliSecrets.map((data)=>{
                                            if(data) {
                                                return (
                                                    <tr>
                                                        <td><TCheckbox lay-skin="primary" data={data}
                                                                       tableRef={this.refs.tableAli}
                                                                       onClick={(checked) => this.aliCheck(checked, data)}/>
                                                        </td>
                                                        <td>{data.mchId}</td>
                                                    </tr>
                                                )
                                            }
                                        }):''
                                    }
                                    </tbody>
                                </Table>
                            </Col>

                        </Row>
                        <Row>
                            <Col md="2" sm="2" md-offset="5" sm-offset="5">
                                <Button size="sm" onClick={()=>this.saveGroup()} style={{width:'100%'}} lay-submit="true">保存</Button>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
                <Modal title="支付功能选择" ref="modalAssign">
                    <Form type="pane" size="sm">
                        <Item>
                        <LayuiCommSelect mask={['building', 'unit', 'floor', 'room']}
                                         ref="commSelectSearch"
                                         formLabelName="小区"
                                         onChangeComm={(comm) => this.commChange(comm)}/>
                        </Item>
                        {found === 1 ?
                            <Table ref="tablePayModule"
                                   checkboxRenderCallback={() => {
                                       this.setState({})
                                   }}
                                   checkboxKeyname="id"
                                   pageData={this.state.payModuleInfos}
                                   toolbar={[<Button size="sm" onClick={()=>this.saveAssign()}>确定保存</Button>]}
                            >
                                <thead>
                                <tr>
                                    <th><TCheckbox  checkAll="true" tableRef={this.refs.tablePayModule}/></th>
                                    <th>功能名</th>
                                    <th>功能实体</th>
                                </tr>
                                </thead>
                                <tbody>
                                {
                                    this.state.payModuleInfos.length > 0 ? this.state.payModuleInfos.map((module) => {
                                        return (
                                            <SecurityCheck perms={this.payAuthority[module.orderType]}>
                                                <tr>
                                                    <td><TCheckbox data={module} tableRef={this.refs.tablePayModule}/>
                                                    </td>
                                                    <td>{module.orderDesc}</td>
                                                    <td>{module.name}</td>
                                                </tr>
                                            </SecurityCheck>
                                        )
                                    }) : ''
                                }
                                </tbody>
                            </Table>
                            : <span>您没有开通对应模块的权限，请开通后再分配</span>
                        }
                    </Form>
                </Modal>
            </Frame>
        )

    }

}

ReactDOM.render(<PayCustAssignModule/>,document.getElementById("assignModule"));